﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace SanctusSoftware.Music.Lyrics.Extraction
{
    
    public class CyberHymnalExtractor : WebSongLyricsExtractor
    {





        protected override string GetRawLyrics(string pageText)
        {




            // Try DIV first
            string rawLyrics = Regex.Match(pageText, "[<]div[ ]class=\"lyrics\"[>](?<Lyrics>(\\W|\\w)+?)[<][/]div[>]").Groups["Lyrics"].Value;

            // Try TD Next
            if (string.IsNullOrEmpty(rawLyrics))
            {
                rawLyrics = Regex.Match(pageText, "[<]td[ ]class=\"lyrics\"[>](?<Lyrics>(\\W|\\w)+?)[<][/]td[>]").Groups["Lyrics"].Value;


            }

            return rawLyrics;

        }

        protected override string GetSongTitle(string pageText)
        {
            return GetTextBetweenTags(pageText, "title", true);
            //            return Regex.Match(pageText, "[<]title[>](?<Title>.*)[<]/title[>]").Groups["Title"].Value;
        }

        protected override string[] GetVerses(string rawLyrics)
        {

            // TODO: Do all clean-up in parent class


            // Eliminate BR Tags
            rawLyrics = Regex.Replace(rawLyrics, @"[<]br[ ]??[/]??[>]", "");

            // Eliminate Opening P Tags
            rawLyrics = Regex.Replace(rawLyrics, "[<]p([ ]*[a-zA-Z]*=\"[^\"]+\")??[>]", "");

            // TODO: keep first instance of refrain and put it with the chorus
            rawLyrics = rawLyrics.Replace(System.Environment.NewLine + "Refrain" + System.Environment.NewLine, "");

            // Replace Closing P tags with CR+LF
            //rawLyrics = Regex.Replace(rawLyrics, @"[<][/]p[>]", System.Environment.NewLine);
            List<string> parts = new List<string>(Regex.Split(rawLyrics, @"[<][/]p[>]"));

            for (int i = 0; i < parts.Count; i++)
            {
                parts[i] = parts[i].Trim(new char[] { '\r', '\n' });
            }

            for (int i = parts.Count - 1; i >= 0; i--)
            {
                if (parts[i].Trim().Length == 0)
                {
                    parts.RemoveAt(i);
                }
            }
            
            return parts.ToArray();


            return rawLyrics.Split(new string[] { System.Environment.NewLine + System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

        }


    }

}
